package com.fawkes.project.example.common.exception;

import com.fawkes.core.base.api.ApiResponseBody;
import com.fawkes.core.enums.BizCodeMsgEnum;
import com.fawkes.core.exception.BusinessException;
import com.fawkes.core.log.utils.LogTool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 统一异常处理
 *
 * @author zhanghutao
 * @version 1.0
 * @date 2019-5-5 19:34
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {
    @Resource
    private LogTool logTool;

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Object handle(Exception e, HttpServletRequest request) {
        BizCodeMsgEnum bizCodeMsgEnum;
        if (e instanceof BusinessException) {
            BusinessException businessException = (BusinessException) e;
            bizCodeMsgEnum = businessException.bizCodeMsgEnum;
        } else {
            bizCodeMsgEnum = BizCodeMsgEnum.SYS_ERROR;
        }
        e.printStackTrace();
        logTool.exceptionLog(e);
        return ApiResponseBody.error(bizCodeMsgEnum);
    }
}
